package com.course.cases;

import com.alibaba.fastjson.JSON;
import com.course.config.TestConfig;
import com.course.model.AddUser;
import com.course.model.User;
import com.course.utils.DatabaseUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.session.SqlSession;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.IOException;

/**
 * @author bigFish
 * @Title:
 */
public class AddController {

    @Test(dependsOnGroups = "loginTrue", description = "添加用户接口")
    public void addUser() throws IOException {
        //1.从数据库获取用例
        SqlSession sqlSession = DatabaseUtil.getSqlSession();
        AddUser addUserCase = sqlSession.selectOne("addUserCase", 1);
        System.out.println(addUserCase);
        //2.发起请求,获取响应结果
        String result = getResult(addUserCase);
        //3.查看是否添加成功
        User user = sqlSession.selectOne("addUser", addUserCase);
        System.out.println(user);
        //4.处理用例结果
        Assert.assertEquals(addUserCase.getExpected(), result);
    }

    private String getResult(AddUser addUserCase) throws IOException {
        HttpPost httpPost = new HttpPost(TestConfig.addUserUrl);
        String param = JSON.toJSONString(addUserCase);
        System.out.println(param);
        //设置请求头
        httpPost.setHeader("content-type", "application/json");
        //把参数添加到方法中
        StringEntity stringEntity = new StringEntity(param, "utf-8");
        httpPost.setEntity(stringEntity);
        //发起请求
        CloseableHttpResponse execute = TestConfig.closeableHttpClient.execute(httpPost);
        //把结果转换为string类型
        String result = EntityUtils.toString(execute.getEntity(),"utf-8");
        System.out.println(result);
        return result;
    }
}
